package com.whz.governance.validate;

import com.alibaba.fastjson.JSON;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * validate whether string is list of the target class
 *
 * @author whz
 */
public class ListOfJsonValidator implements ConstraintValidator<ListOfJson, CharSequence> {
    private Class<?> targetClass;

    @Override
    public void initialize(ListOfJson annotation) {
        targetClass = annotation.targetClass();
    }

    @Override
    public boolean isValid(CharSequence value, ConstraintValidatorContext context) {
        if (value == null) {
            return true;
        }
        return canConvert(value.toString());
    }

    private boolean canConvert(String json) {
        try {
            JSON.parseArray(json, targetClass);
            return true;
        } catch (Exception ignored) {
        }
        return false;
    }
}